<template>
  <GlobalDrawer
    v-model="visible"
    :title="formTitle"
    size="80%"
    :show-footer-buttons="true"
    @confirm="handleSubmit"
  >
    <el-form
      ref="formRef"
      :model="lawsuitForm"
      :rules="lawsuitRules"
      label-width="100px"
      v-loading="loading"
    >
      <!-- 引入公共表单 -->
      <OrderCommonForm
        ref="commonFormRef"
        :customer-id="props.customerId"
        :order-data="props.orderId ? orderData : {}"
      />

      <el-divider content-position="left">诉讼订单信息</el-divider>

      <!-- 诉讼订单特有字段 -->
      <el-form-item label="首单体验" prop="is_first_order">
        <el-radio-group v-model="lawsuitForm.is_first_order">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="下单类型" prop="order_type">
        <el-radio-group v-model="lawsuitForm.order_type">
          <el-radio :label="1">案件代理</el-radio>
          <el-radio :label="2">诉讼指导</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="委托方" prop="entrusting_party_type">
        <el-radio-group v-model="lawsuitForm.entrusting_party_type">
          <el-radio :label="1">原告</el-radio>
          <el-radio :label="2">被告</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="委托方名称" prop="entrusting_party_name">
        <el-input v-model="lawsuitForm.entrusting_party_name" placeholder="请输入委托方名称" />
      </el-form-item>

      <el-form-item label="相对方" prop="opposing_party_type">
        <el-radio-group v-model="lawsuitForm.opposing_party_type">
          <el-radio :label="1">原告</el-radio>
          <el-radio :label="2">被告</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="相对方名称" prop="opposing_party_name">
        <el-input v-model="lawsuitForm.opposing_party_name" placeholder="请输入相对方名称" />
      </el-form-item>

      <el-form-item label="联系人" prop="contact_person">
        <el-input v-model="lawsuitForm.contact_person" placeholder="请输入联系人" />
      </el-form-item>

      <el-form-item label="联系电话">
        <el-input v-model="lawsuitForm.contact_phone" placeholder="请输入联系电话" />
      </el-form-item>

      <el-form-item label="前期费用" prop="service_fee_pre">
        <el-input-number
          v-model="lawsuitForm.service_fee_pre"
          :min="0"
          :precision="2"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="后期费用">
        <el-input-number
          v-model="lawsuitForm.service_fee_post"
          :min="0"
          :precision="2"
          style="width: 100%"
        />
        <div class="el-form-item__help">回款后付</div>
      </el-form-item>

      <el-form-item label="案由" prop="case_type">
        <el-checkbox-group v-model="lawsuitForm.case_type">
          <el-checkbox :label="1">合同</el-checkbox>
          <el-checkbox :label="2">股权</el-checkbox>
          <el-checkbox :label="3">劳动</el-checkbox>
          <el-checkbox :label="4">金融</el-checkbox>
          <el-checkbox :label="5">借贷</el-checkbox>
          <el-checkbox :label="6">工伤</el-checkbox>
          <el-checkbox :label="7">婚姻</el-checkbox>
          <el-checkbox :label="8">刑事</el-checkbox>
          <el-checkbox :label="9">破产</el-checkbox>
          <el-checkbox :label="10">其他</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item v-if="lawsuitForm.case_type.includes(10)" label="其他案由">
        <el-input v-model="lawsuitForm.case_type_other" placeholder="请输入其他案由" />
      </el-form-item>

      <el-form-item label="民商阶段">
        <el-checkbox-group v-model="lawsuitForm.civil_phase">
          <el-checkbox label="仲裁">仲裁</el-checkbox>
          <el-checkbox label="一审">一审</el-checkbox>
          <el-checkbox label="二审">二审</el-checkbox>
          <el-checkbox label="再审">再审</el-checkbox>
          <el-checkbox label="执行">执行</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="刑事阶段">
        <el-checkbox-group v-model="lawsuitForm.criminal_phase">
          <el-checkbox label="会见">会见</el-checkbox>
          <el-checkbox label="上诉">上诉</el-checkbox>
          <el-checkbox label="公安">公安</el-checkbox>
          <el-checkbox label="检察院">检察院</el-checkbox>
          <el-checkbox label="法院">法院</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="标的金额" prop="case_amount_range">
        <el-radio-group v-model="lawsuitForm.case_amount_range">
          <el-radio :label="1">5万以下</el-radio>
          <el-radio :label="2">5-10万</el-radio>
          <el-radio :label="3">10-50万</el-radio>
          <el-radio :label="4">50-100万</el-radio>
          <el-radio :label="5">100万以上</el-radio>
          <el-radio :label="6">其他</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item v-if="lawsuitForm.case_amount_range === 6" label="其他金额">
        <el-input v-model="lawsuitForm.case_amount_other" placeholder="请输入其他金额" />
      </el-form-item>

      <el-form-item label="诉讼请求要素">
        <el-checkbox-group v-model="lawsuitForm.lawsuit_request_elements">
          <el-checkbox label="违约金">违约金</el-checkbox>
          <el-checkbox label="利息">利息</el-checkbox>
          <el-checkbox label="诉讼费">诉讼费</el-checkbox>
          <el-checkbox label="律师费">律师费</el-checkbox>
          <el-checkbox label="保全费">保全费</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="主要诉讼请求">
        <el-input
          v-model="lawsuitForm.main_lawsuit_request"
          type="textarea"
          :rows="4"
          placeholder="请输入主要诉讼请求"
        />
      </el-form-item>
    </el-form>
  </GlobalDrawer>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, onMounted, nextTick } from 'vue'
  import { ElMessage } from 'element-plus'
  import GlobalDrawer from '@/components/common/GlobalDrawer.vue'
  import OrderCommonForm from './common/OrderCommonForm.vue'
  import { lawsuitLegalOrderApi } from '@/api/crm/lawsuitLegalOrderApi'

  // Props定义
  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
    },
    orderId: {
      type: Number,
      default: 0,
    },
    customerId: {
      type: Number,
      default: 0,
    },
  })

  // Emits定义
  const emit = defineEmits(['update:modelValue', 'success'])

  // 响应式数据
  const visible = computed({
    get: () => props.modelValue,
    set: value => emit('update:modelValue', value),
  })

  const loading = ref(false)
  const formRef = ref()
  const commonFormRef = ref()
  const orderData = ref({})

  // 诉讼订单特有表单数据
  const lawsuitForm = reactive({
    is_first_order: 0,
    order_type: 1,
    entrusting_party_type: 1,
    entrusting_party_name: '',
    opposing_party_type: 2,
    opposing_party_name: '',
    contact_person: '',
    contact_phone: '',
    service_fee_pre: 0,
    service_fee_post: 0,
    case_type: [] as number[],
    case_type_other: '',
    civil_phase: [] as string[],
    criminal_phase: [] as string[],
    case_amount_range: 1,
    case_amount_other: '',
    lawsuit_request_elements: [] as string[],
    main_lawsuit_request: '',
  })

  // 诉讼订单特有验证规则
  const lawsuitRules = {
    is_first_order: [{ required: true, message: '请选择是否首单体验', trigger: 'change' }],
    order_type: [{ required: true, message: '请选择下单类型', trigger: 'change' }],
    entrusting_party_type: [{ required: true, message: '请选择委托方', trigger: 'change' }],
    entrusting_party_name: [{ required: true, message: '请输入委托方名称', trigger: 'blur' }],
    opposing_party_type: [{ required: true, message: '请选择相对方', trigger: 'change' }],
    opposing_party_name: [{ required: true, message: '请输入相对方名称', trigger: 'blur' }],
    contact_person: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
    service_fee_pre: [{ required: true, message: '请输入前期费用', trigger: 'blur' }],
    case_type: [
      { required: true, message: '请选择案由', trigger: 'change' },
      { type: 'array', min: 1, message: '至少选择一个案由', trigger: 'change' },
    ],
    case_amount_range: [{ required: true, message: '请选择标的金额', trigger: 'change' }],
  }

  // 表单标题
  const formTitle = computed(() => {
    return props.orderId ? '编辑诉讼订单' : '新增诉讼订单'
  })

  // 获取订单详情
  const getOrderDetail = async () => {
    if (!props.orderId) return

    loading.value = true
    try {
      const res = await lawsuitLegalOrderApi.getLawsuitOrderDetail(props.orderId)
      orderData.value = res.data

      // 填充诉讼特有数据
      Object.keys(lawsuitForm).forEach(key => {
        if ((res.data as any)[key] !== undefined) {
          ;(lawsuitForm as any)[key] = (res.data as any)[key]
        }
      })

      // 等待公共表单初始化完成
      await nextTick()
      if (commonFormRef.value) {
        commonFormRef.value.initData()
      }
    } catch (error) {
      console.error('获取订单详情失败:', error)
      ElMessage.error('获取订单详情失败')
    } finally {
      loading.value = false
    }
  }

  // 提交表单
  const handleSubmit = async () => {
    // 验证公共表单
    if (commonFormRef.value && commonFormRef.value.formRef) {
      const valid = await commonFormRef.value.formRef.validate()
      if (!valid) return
    }

    // 验证诉讼特有表单
    if (!formRef.value) return
    const valid = await formRef.value.validate()
    if (!valid) return

    loading.value = true
    try {
      // 获取公共表单数据
      const commonData = commonFormRef.value?.getFormData() || {}

      // 合并数据
      const submitData = {
        ...commonData,
        ...lawsuitForm,
        order_category: 2, // 诉讼订单类别
        opportunity_id: props.orderId || 0,
      }

      // 根据是否有订单ID决定是新增还是编辑
      if (props.orderId) {
        await lawsuitLegalOrderApi.saveLawsuitOrder({ ...submitData, id: props.orderId })
        ElMessage.success('更新成功')
      } else {
        await lawsuitLegalOrderApi.create(submitData)
        ElMessage.success('创建成功')
      }

      // 触发成功事件
      emit('success')
      handleClose()
    } catch (error) {
      console.error('提交失败:', error)
      ElMessage.error('提交失败，请重试')
    } finally {
      loading.value = false
    }
  }

  // 关闭抽屉
  const handleClose = () => {
    visible.value = false
    // 重置表单
    resetForm()
  }

  // 重置表单
  const resetForm = () => {
    if (formRef.value) {
      formRef.value.resetFields()
    }

    if (commonFormRef.value) {
      commonFormRef.value.resetForm()
    }

    // 重置诉讼特有表单
    lawsuitForm.is_first_order = 0
    lawsuitForm.order_type = 1
    lawsuitForm.entrusting_party_type = 1
    lawsuitForm.entrusting_party_name = ''
    lawsuitForm.opposing_party_type = 2
    lawsuitForm.opposing_party_name = ''
    lawsuitForm.contact_person = ''
    lawsuitForm.contact_phone = ''
    lawsuitForm.service_fee_pre = 0
    lawsuitForm.service_fee_post = 0
    lawsuitForm.case_type = []
    lawsuitForm.case_type_other = ''
    lawsuitForm.civil_phase = []
    lawsuitForm.criminal_phase = []
    lawsuitForm.case_amount_range = 1
    lawsuitForm.case_amount_other = ''
    lawsuitForm.lawsuit_request_elements = []
    lawsuitForm.main_lawsuit_request = ''
  }

  // 监听visible变化
  const unwatch = computed(() => props.modelValue)
  const watchVisible = () => {
    if (props.modelValue && props.orderId) {
      getOrderDetail()
    }
  }

  // 组件挂载时
  onMounted(() => {
    // 如果打开时就有订单ID，获取订单详情
    if (props.modelValue && props.orderId) {
      getOrderDetail()
    }
  })
</script>

<style scoped>
  /* 可以添加特定样式 */
</style>
